<template>
  
    <el-container :style="{ height: containerHeight + 'px' }">
    <!-- 左侧部门树形菜单列表 -->
    <el-aside style="
      padding: 10px 0px 0px 0px;
      background: #fff;
      border-right: 1px solid #dfe6ec;
      "
      width="200px"
      >
        <el-tree
          style="font-size: 14px"
          ref="leftTree"
          :data="deptList"
          node-key="id"
          :props="defaultProps"
          default-expand-all
          empty-text="暂无数据"
          :show-checkbox="false"
          :highlight-current="true"
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
        >
          <div class="custom-tree-node" slot-scope="{ node, data }">
            <div>
              <span v-if="data.children.length == 0">
                <i class="el-icon-document"></i>
              </span>
              <span v-else @click.stop="openBtn(data)">
                <svg-icon v-if="data.open" icon-class="add-s"/>
                <svg-icon v-else icon-class="sub-s"/>
              </span>
              <span style="margin-left: 3px">{{ node.label }}</span>
            </div>
          </div>
        </el-tree>      
      </el-aside>
    
  <el-main>
    <el-form
    :model="searchModel"
    ref="searchForm"
    label-width="80px"
    :inline="true"
    size="small"
    >
    <el-form-item>
      <el-input v-model="searchModel.username" placeholder="请输入用户名"/>
    </el-form-item>
    <el-form-item>
      <el-input v-model="searchModel.realName" placeholder="请输入真实姓名"/>
    </el-form-item>
    <el-form-item>
      <el-input v-model="searchModel.phone" placeholder="请输入电话"/>
    </el-form-item>
    <el-form-item>
      <el-button icon="el-icon-search" type="primary" @click="search(departmentId, pageNo, pageSize)">查询</el-button>
      <el-button icon="el-icon-delete" @click="resetValue()">重置</el-button>
      <el-button icon="el-icon-plus" size="small" type="success" @click="openAddWindow()">新增</el-button>
    </el-form-item>            
    </el-form>
    <el-table
      :height="tableHeight"
      :data="userList"
      border
      stripe
      style="width: 100%; margin-bottom: 10px"
    >
    <el-table-column prop="username" label="用户名"></el-table-column>
    <el-table-column prop="realName" label="姓名"></el-table-column>
    <el-table-column prop="departmentName" label="所属部门"></el-table-column>
    <el-table-column prop="phone" label="电话"></el-table-column>
    <el-table-column prop="email" label="邮箱"></el-table-column>
    <el-table-column align="center" width="290" label="操作">
      <template slot-scope="scope">
        <el-button icon="el-icon-edit" type="primary" size="mini" @click="handleEdit(scope.row)" >编辑</el-button>
        <el-button icon="el-icon-delete" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        <el-button icon="el-icon-setting" type="primary" size="mini" @click="assignRole(scope.row)">分配角色</el-button>
      </template>
    </el-table-column>
    </el-table>
    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNo"
      :page-sizes="[10, 20, 30, 40, 50]"
      :page-size="10"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>    

  <!-- 上级部门弹框 -->
  <system-dialog
    :title="parentDialog.title"
    :width="parentDialog.width"
    :height="parentDialog.height"
    :visible="parentDialog.visible"
    @onClose="onParentClose"
    @onConfirm="onParentConfirm"
  >
  <div slot="content">
    <el-tree 
      ref="parentTree"
      :data="parentList"
      default-expand-all
      node-key="id"
      :props="parentProps"
      :show-checkbox="false"
      :highlight-current="true"
      :expand-on-click-node="false"
      @node-click="parentClick"
    >
    <div class="customer-tree-node" slot-scope="{ node, data }">
      <span v-if="data.children.length == 0">
        <i class="el-icon-document"/>
      </span>
      <span v-else @click.stop="openParentBtn(data)">
        <svg-icon v-if="data.open" icon-class="add-s"/>
        <svg-icon v-else icon-class="sub-s" />
      </span>
      <span style="margin-left: 3px">{{ node.label }}</span>
    </div>
    </el-tree>
  </div>   
  </system-dialog>

  <system-dialog
    :title="userDialog.title"
    :height="userDialog.height"
    :width="userDialog.width"
    :visible="userDialog.visible"
    @onClose="onClose"
    @onConfirm="onConfirm"
  >
    <div slot="content">
      <el-form
        :model="user"
        ref="userForm"
        :rules="rules"
        label-width="80px"
        :inline="true"
        size="small"
      >
      <el-form-item prop="username" label="用户名">
        <el-input v-model="user.username"></el-input>
      </el-form-item>
      <el-form-item prop="password" v-if="user.id === ''" label="密码">
        <el-input type="password" v-model="user.password"></el-input>
      </el-form-item>
      <el-form-item prop="departmentName" label="所属部门">
        <el-input
          v-model="user.departmentName"
          :readonly="true"
          @click.native="selectDepartment()"
        ></el-input>
      </el-form-item>
      <el-form-item prop="realName" label="姓名">
        <el-input v-model="user.realName"></el-input>
      </el-form-item>
      <el-form-item prop="phone" label="电话">
        <el-input v-model="user.phone"></el-input>
      </el-form-item>
      <el-form-item label="昵称">
        <el-input v-model="user.nickName"></el-input>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="user.email"></el-input>
      </el-form-item>
      <el-form-item prop="gender" label="性别">
        <el-radio-group v-model="user.gender">
          <el-radio :label="0">男</el-radio>
          <el-radio :label="1">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <br>
      <!--用户头像-->
      </el-form>    
    </div>
  </system-dialog>
  <system-dialog
    :title="assignDialog.title"
    :height="assignDialog.height"
    :width="assignDialog.width"
    :visible="assignDialog.visible"
    @onClose="onAssignClose"
    @onConfirm="onAssignConfirm"  
  >
  <div slot="content">
    <el-table
      ref="assignRoleTable"
      :data="assignRoleList"
      border
      stripe
      :height="assignHeight"
      style="width: 100%; margin-bottom: 10px"
      @selection-change="handleSelectionChange"   
    >
    <el-table-column
    type="selection"
    width="55"
    align="center"></el-table-column>
      <el-table-column prop="roleCode" label="角色编码"/>
      <el-table-column prop="roleName" label="角色名称"/>
      <el-table-column prop="remark" label="角色备注"/>    
    
    </el-table>
    <el-pagination
      @size-change="assignSizeChange"
      @current-change="assignCurrentChange"
      :current-page.sync="roleVo.pageNo"
      :page-sizes="[10, 20, 30, 40, 50]"
      :page-size="roleVo.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="roleVo.total"
      background
    ></el-pagination>    
    </div>

  </system-dialog>
    </el-main>
  </el-container>
</template>

<script>
import departmentApi from '@/api/department';
import userApi from '@/api/user';
// 导入对话框组件
import SystemDialog from '@/components/system/SystemDialog.vue'
export default {
  name: 'userList',
  // 组件注册
  components: {
    SystemDialog
  },
  data() {
    return {
      containerHeight: 0, //容器高度
      deptList: [], //左侧部门树形菜单列表
      userList: [], //用户列表
      tableHeight: 0, //表格高度
      pageNo: 1, //当前页码
      pageSize: 10, //每页显示数量
      total: 0, //总数量
      departmentId: "", //部门编号      
      defaultProps: {
        children: 'children',
        label: 'departmentName'
      },
      searchModel: {
        username: "",
        realName:"",
        phone: "",
        departmentId: "",
        pageNo: 1,
        pageSize: 10,
      },
      userDialog: {
        title: '',
        height: 410,
        width: 610,
        visible: false
      },
      parentDialog: {
        title: '选择所属部门',
        width: 300,
        height: 450,
        visible: false
      },
      assignDialog:{
        title: "",
        visible: false,
        width: 800,
        height: 410        
      },
      roleVo: {
        pageNo: 1,
        pageSize: 10,
        userId: "",
        total: 0,        
      },
        assignRoleList: [], //角色列表
        assignHeight: 0, //分配角色表格高度
        selectedIds: [], //被选中的角色id
        selectedUserId: "", //被分配角色的用户ID      
      parentProps: {
        children: 'children',
        label: 'departmentName'
      },
      parentList: [], //所属部门节点数据
      user: {
        id: '',
        departmentId: '',
        departmentName: '',
        email: '',
        realName: '',
        phone: '',
        nickName: '',
        password: '',
        username: '',
        gender: '',
        avatar:''
      },
      rules:{
        departmentName: [{ required: true, trigger: 'change', message: '请选择所属部门' }],
        realName: [{ required: true, trigger: 'blur', message: '请填写姓名' }],
        phone: [{ required: true, trigger: 'blur', message: '请填写电话号码' }],
        username: [{ required: true, trigger: 'blur', message: '请填写登录名' }],
        password: [{ required: true, trigger: 'blur', message: '请填写登录密码' }],
        gender: [{ required: true, trigger: 'change', message: '请选择性别' }]        
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.containerHeight = window.innerHeight - 85;
      this.tableHeight = window.innerHeight - 220;
      this.assignHeight = window.innerHeight - 350;
    })
  },
  created() {
    // 调用查询用户列表的方法
    this.getDeptList();
    this.search(this.departmentId);
  },
  methods: {
    async getDeptList(){
      let res = await departmentApi.getDepartmentList(null);
      if(res.success){
        this.deptList = res.data
        this.$nextTick(() => {
          const firstNode = document.querySelector(".el-tree-node");
          firstNode.click();
        });
      }
    },
    handleNodeClick(data){
      this.departmentId = data.id;
      this.search(this.departmentId);
    },
    async search(departmentId, pageNo = 1, pageSize = 10) {
      this.searchModel.pageNo = pageNo;
      this.searchModel.pageSize = pageSize;
      this.searchModel.departmentId = departmentId;
      let res = await userApi.getUserList(this.searchModel);
      if (res.success) {
        this.userList = res.data.records;
        this.total = res.data.total;
      }
    },
    handleSizeChange(size) {
      this.pageSize = size; //将每页显示的数量交给成员变量
      this.search(this.departmentId, this.pageNo, size);
    },
    handleCurrentChange(page) {
      this.pageNo = page;
      //调用查询方法
      this.search(this.departmentId, page, this.pageSize);
    },
    resetValue(){
      this.searchModel = {};
      this.search(this.departmentId);
    },
    openBtn(data){
      data.open = !data.open
      this.$refs.leftTree.store.nodesMap[data.id].expanded = !data.open;
    },
    openAddWindow(){
      this.$resetForm('userForm', this.user) //清空表单
      this.userDialog.visible = true //显示窗口
      this.userDialog.title = '新增用户' //设置标题      
    },
    onClose() {
      this.userDialog.visible = false //关闭窗口
    },
    onConfirm() {
      this.$refs.userForm.validate(async (valid) => {
        if (valid) {
          let res = null
          if (this.user.id === '') {
            res = await userApi.addUser(this.user)
          }else{
            res = await userApi.updateUser(this.user)
          }
          if (res.success) {
            this.$message.success(res.message)
            this.search(this.departmentId)
            this.userDialog.visible = false
          }else{
            this.$message.error(res.message)
          }
        }
      })
    },
    async selectDepartment(){
      let res = await departmentApi.getDepartmentList(null)
      if (res.success) {
        this.parentList = res.data
      }
      this.parentDialog.visible = true
    },
    onParentClose() {
      this.parentDialog.visible = false //关闭窗口
    },
    onParentConfirm() {
      this.parentDialog.visible = false
    },
    parentClick(data) {
      this.user.departmentId = data.id
      this.user.departmentName = data.departmentName
    },
    openParentBtn(data) {
      data.open = !data.open
      this.$refs.parentTree.store.nodesMap[data.id].expanded = !data.open
    },
    handleEdit(row){
      this.userDialog.title = '编辑用户'
      this.userDialog.visible = true
      this.$objCopy(row, this.user)
    },
    async handleDelete(row){
      let confirm = await this.$myconfirm('确定要删除该数据吗?')
      if (confirm){
        let params = { id: row.id }
        let res = await userApi.deleteUser(params)
        if (res.success){
          this.$message.success(res.message)
          this.search(this.departmentId)
        }else{
          this.$message.error(res.message)
        }
      }
    },
    async assignRole(row){
      this.selectedIds = [];
      this.selectedUserId = "";
      //被分配用户的id
      this.selectedUserId = row.id;
      //显示窗口
      this.assignDialog.visible = true;
      //设置标题
      this.assignDialog.title = `给【${row.realName}】分配角色`;
      //查询当前登录用户的所有角色信息
      await this.getAssignRoleList();
      //获取当前被分配用户的ID
      let params = {
        userId: row.id,
      }
      let res = await userApi.getRoleIdByUserId(params);
      if (res.success && res.data){
        this.selectedIds = res.data;
        this.selectedIds.forEach((key) => {
          this.assignRoleList.forEach((item) => {
            if (item.id === key){
              this.$refs.assignRoleTable.toggleRowSelection(item, true);
            }
          })
        })
      }
        
    },
    async getAssignRoleList(pageNo = 1, pageSize = 10){
      //给用户ID赋值
      this.roleVo.userId = this.$store.getters.userId;
      this.roleVo.pageNo = pageNo;
      this.roleVo.pageSize = pageSize;
      //发送查询请求
      let res = await userApi.getAssignRoleList(this.roleVo);
      //判断是否成功
      if (res.success){
        this.assignRoleList = res.data.records;
        this.roleVo.total = res.data.total;
      }
    },
    onAssignClose(){
      this.assignDialog.visible = false;
    },
    async onAssignConfirm(){
      if (this.selectedIds.length === 0){
        this.$message.warning("请选择要分配的角色！");
        return;
      }
      let params = {
        userId: this.selectedUserId,
        roleIds: this.selectedIds,
      }
      let res = await userApi.assignRoleSave(params);
      if (res.success) {
        this.$message.success(res.message);
        this.assignDialog.visible = false;
      }else{
        this.$message.error(res.message);
      }
      
    },
    assignSizeChange(size){
      this.roleVo.pageSize = size; //将每页显示的数量交给成员变量
      this.getAssignRoleList(this.roleVo.pageNo, size);
    },
    assignCurrentChange(page){
      this.roleVo.pageNo = page;
      this.getAssignRoleList(page, this.roleVo.pageSize);
    },
    handleSelectionChange(rows){
      let roleIds = [];
      for (let i = 0; i < rows.length; i++){
        roleIds.push(rows[i].id);
      }
      console.log(roleIds+'*****************************')
      this.selectedIds = roleIds;
    }
  }

}

</script>

<style lang="scss" scoped></style>
